package com.miplus.ccrm.sms;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataUnit;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Slf4j
@Service
public class JSmsService {
    @Value("${ccrm.sms.url}")
    private String smsUrl;

    //渠道类型
    @Value("${ccrm.sms.channel}")
    private String smsChannel;

    //调用方系统Id
    @Value("${ccrm.sms.source}")
    private String smsSource;

    //产品号
    @Value("${ccrm.sms.prod}")
    private String smsProdId;

    //业务归属
    @Value("${ccrm.sms.busitype}")
    private String smsbusiType;

    public JSmsService()
    {

    }


    //单个发送短信
    public SmsR SendSmsArray(String msgid,String phone,String[] content){
        JSONObject objJson=new JSONObject();
        Date currentDate =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmssSSS");
        SimpleDateFormat TxnDtF = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat MsgSndTmF = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        Random random=new Random();
        String tDt=sdf.format(currentDate)+(100+random.nextInt(900));
        String TxnDt= TxnDtF.format(currentDate);
        String MsgSndTm = MsgSndTmF.format(currentDate);

        JSONObject headJson=new JSONObject();
        headJson.put("SvcCd","50320001");
        headJson.put("SvcScn","01");
        headJson.put("UsrLng","CHINESE");
        headJson.put("MdulId","RB");
        headJson.put("CnlTp","07");
        headJson.put("CnsmrSysId","101500");
        headJson.put("CnsmrSeqNo",tDt);
        headJson.put("BsnSeqNo",tDt);
        headJson.put("SrcCnsmrSysId","100900");
        headJson.put("SrcCnsmrSeqNo",tDt);
        headJson.put("TxnDt",TxnDt);//时间戳
        headJson.put("TxnTm","195242800");
        headJson.put("CnsmrSvrId","");
        headJson.put("FileFlg","0");
        headJson.put("InstId","50801");
        headJson.put("TlrNo","V0016");

        objJson.put("Head",headJson);
        JSONObject bodyJson=new JSONObject();
        bodyJson.put("MblNo",phone);
        bodyJson.put("ShrtMsgCntntDscArry",content);
        bodyJson.put("CnlSrlNo",tDt);
        bodyJson.put("TmlSrlNo","NDCS20241118104442");
        bodyJson.put("MsgSndTm",MsgSndTm);
        bodyJson.put("BsnCd",msgid);
        bodyJson.put("RqsSysNo","NDCS");
        objJson.put("Body",bodyJson);

        String requestBody=objJson.toJSONString();

//        log.info("SendSms:{}",requestBody);


        try {
            String sendUrl=smsUrl+"/NDCS/sendSMS";
            // 发送 POST 请求
            HttpResponse<JsonNode> jsonResponse = Unirest.post(sendUrl)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body(requestBody)
                    .asJson();

            int status = jsonResponse.getStatus();
            if (status == 200) {
                log.info("SendSms.Response:{}", jsonResponse.getBody());

                String retCd = JSONObject.parseObject(jsonResponse.getBody().getObject()
                        .get("Head").toString()).get("TxnSt").toString();
                if(!retCd.equals("1")){
                    String retMsg = JSONObject.parseObject(jsonResponse.getBody().getObject()
                            .get("Head").toString()).get("RetMsg").toString();
                    return SmsR.Error(302,retMsg);
                }

                return SmsR.Success("ok");
            } else {
                log.warn("SendSms.Fail:Status={},Cause={}", status, jsonResponse.getStatusText());
                return SmsR.Error(status,jsonResponse.getStatusText());
            }
        }
        catch (Exception e){
            log.warn("SendSms.Err:{}", e.getMessage());

            return SmsR.Error(-1,e.getMessage());
        }
    }







    /**
     * 批量发送短信
     * @param msgid
     * @param mblNoArry  [{"MblNo":"152...",
     *                     "ParmStrg":"{cust_name:汪昊,gender:先生}"
     *                   }]
     * @return
     */
    public SmsR SendSmsArrayBath(String msgid,JSONArray mblNoArry){

        JSONObject objJson=new JSONObject();
        Date currentDate =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMddHHmmssSSS");
        SimpleDateFormat TxnDtF = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat MsgSndTmF = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        Random random=new Random();
        String tDt=sdf.format(currentDate)+(100+random.nextInt(900));
        String TxnDt= TxnDtF.format(currentDate);
        String MsgSndTm = MsgSndTmF.format(currentDate);

        JSONObject headJson=new JSONObject();
        headJson.put("SvcCd","50320001");
        headJson.put("SvcScn","03");
        headJson.put("UsrLng","CHINESE");
        headJson.put("MdulId","RB");
        headJson.put("CnlTp","07");
        headJson.put("CnsmrSysId","101500");
        headJson.put("CnsmrSeqNo",tDt);
        headJson.put("BsnSeqNo",tDt);
        headJson.put("SrcCnsmrSysId","100900");
        headJson.put("SrcCnsmrSeqNo",tDt);
        headJson.put("TxnDt",TxnDt);//时间戳
        headJson.put("TxnTm","195242800");
        headJson.put("CnsmrSvrId","");
        headJson.put("FileFlg","0");
        headJson.put("InstId","50801");
        headJson.put("TlrNo","V0016");

        objJson.put("Head",headJson);
        JSONObject bodyJson=new JSONObject();
        bodyJson.put("MblNoArry",mblNoArry);
        bodyJson.put("BsnCd",msgid);
        bodyJson.put("SysNo","NDCS");
        bodyJson.put("MsgSndTm",MsgSndTm);
        objJson.put("Body",bodyJson);

        String requestBody=objJson.toJSONString();

//        log.info("SendSms:{}",requestBody);


        try {
            String sendUrl=smsUrl+"/NDCS/sendSMS";
            // 发送 POST 请求
            HttpResponse<JsonNode> jsonResponse = Unirest.post(sendUrl)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body(requestBody)
                    .asJson();

            int status = jsonResponse.getStatus();
            if (status == 200) {
                log.info("SendSms.Response:{}", jsonResponse.getBody());


                String retCd = JSONObject.parseObject(jsonResponse.getBody().getObject()
                        .get("Head").toString()).get("TxnSt").toString();
                if(!retCd.equals("1")){
                    throw new ServiceException(EnumRCode.Exception.value, JSONObject.parseObject(jsonResponse.getBody().getObject()
                            .get("Head").toString()).get("RetMsg").toString());
                }

                return SmsR.Success("ok");
            } else {
                log.warn("SendSms.Fail:Status={},Cause={}", status, jsonResponse.getStatusText());
                return SmsR.Error(status,jsonResponse.getStatusText());
            }
        }
        catch (Exception e){
            log.warn("SendSms.Err:{}", e.getMessage());

            return SmsR.Error(-1,e.getMessage());
        }
    }


    //发送短信
    public SmsR SendSms(String srvIpaddr,String sysSeqNo,String phone,String content)
    {
        String seqNo=smsChannel+sysSeqNo;

        log.info("SendSms:Ipaddr={},seqNo={}..",srvIpaddr,seqNo);

        JSONObject objJson=new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        JSONObject headJson=new JSONObject();
        headJson.put("chlType",smsChannel);
        headJson.put("svcCd","MSGO0001");
        headJson.put("svcScn","MSGO");
        headJson.put("tranDt",sdf.format(new Date()));
        sdf = new SimpleDateFormat("HHmmssSSS");
        headJson.put("tranTm",sdf.format(new Date()));
        headJson.put("glblSeqNo",seqNo);
        headJson.put("cnsmSysSeqNo",seqNo);
        headJson.put("cnsmSysId",smsSource);
        headJson.put("cnsmSysSvrId",srvIpaddr);

        objJson.put("sysHead",headJson);

        JSONObject bodyJson=new JSONObject();
        bodyJson.put("mobiles",phone);
        bodyJson.put("content",content);
        bodyJson.put("clientId","");
        bodyJson.put("prod",smsProdId);
        bodyJson.put("busiType",smsbusiType);

        objJson.put("body",bodyJson);

        String requestBody=objJson.toJSONString();

        log.info("SendSms:{}",requestBody);

        try {
            String sendUrl=smsUrl+"/MSGO/MSGO0001";
            // 发送 POST 请求
            HttpResponse<JsonNode> jsonResponse = Unirest.post(sendUrl)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body(requestBody)
                    .asJson();

            int status = jsonResponse.getStatus();
            if (status == 200) {
                log.info("SendSms.Response:{}", jsonResponse.getBody());
                return SmsR.Success(seqNo);
            } else {
                log.warn("SendSms.Fail:Status={},Cause={}", status, jsonResponse.getStatusText());
                return SmsR.Error(status,jsonResponse.getStatusText());
            }
        }
        catch (Exception e){
            log.warn("SendSms.Err:{}", e.getMessage());

            return SmsR.Error(-1,e.getMessage());
        }
    }

    //发送模板短信
    public SmsR SendTempSms(String srvIpaddr,String sysSeqNo,String phone,String tmplId,String tmplParm)
    {
        String seqNo=smsChannel+sysSeqNo;

        log.info("SendTempSms:Ipaddr={},seqNo={},tmplId={},tmplParm={}..",srvIpaddr,seqNo,tmplId,tmplParm);

        JSONObject objJson=new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        JSONObject headJson=new JSONObject();
        headJson.put("chlType",smsChannel);
        headJson.put("svcCd","MSGO0007");
        headJson.put("svcScn","MSGO");
        headJson.put("tranDt",sdf.format(new Date()));
        sdf = new SimpleDateFormat("HHmmssSSS");
        headJson.put("tranTm",sdf.format(sdf));
        headJson.put("glblSeqNo",seqNo);
        headJson.put("cnsmSysSeqNo",seqNo);
        headJson.put("cnsmSysId",smsSource);
        headJson.put("cnsmSysSvrId",srvIpaddr);

        objJson.put("sysHead",headJson);

        JSONObject bodyJson=new JSONObject();
        bodyJson.put("tmplId",tmplId);
        bodyJson.put("tmplParm",tmplParm);
        bodyJson.put("mobiles",phone);
        bodyJson.put("clientId","");

        objJson.put("body",bodyJson);

        String requestBody=objJson.toJSONString();

        log.info("SendTempSms:{}",requestBody);

        try {
            String sendUrl=smsUrl+"/MSGO/MSGO0007";
            // 发送 POST 请求
            HttpResponse<JsonNode> jsonResponse = Unirest.post(sendUrl)
                    .header("Content-Type", "application/json;charset=UTF-8")
                    .body(requestBody)
                    .asJson();

            int status = jsonResponse.getStatus();
            if (status == 200) {
                log.info("SendTempSms.Response:{}", jsonResponse.getBody());
                return SmsR.Success(seqNo);
            } else {
                log.warn("SendTempSms.Fail:Status={},Cause={}", status, jsonResponse.getStatusText());
                return SmsR.Error(status,jsonResponse.getStatusText());
            }
        }
        catch (Exception e){
            log.warn("SendTempSms.Err:{}", e.getMessage());

            return SmsR.Error(-1,e.getMessage());
        }
    }
}
